<template lang="pug">
div.password-edit
  Form(ref='form', :label-width=80, :model='formData', :rules='rules', action='javascript:;', @submit='submit')
    FormItem(label='旧密码', prop='currentPass', required, v-if='isEdit')
      Input(type='password', v-model='formData.currentPass')
    FormItem(label='新密码', prop='newPass', required)
      Input(type='password', v-model='formData.newPass')
    FormItem(label='确认密码', prop='confirmPass', required)
      Input(type='password', v-model='formData.confirmPass')
    FormItem
      Button(type='primary', html-type='submit', :loading='loading', long, @click='submit') 修改密码
</template>

<script>
import userApi from '@/apis/user'

export default {
  beforeRouteLeave (to, from, next) {
    if (this.isEdit || this.saved) {
      next()
    } else if (confirm('尚未修改密码，确认离开本页面吗?')) {
      next()
    }
  },
  data () {
    return {
      saved: false,
      loading: false,
      formData: {
        currentPass: '',
        newPass: '',
        confirmPass: ''
      },
      rules: {
        currentPass: { type: 'string', required: true, /* min: 6, */ message: '请输入旧密码', trigger: 'blur' },
        newPass: { type: 'string', required: true, /* min: 6, */ message: '请输入新密码', trigger: 'blur' },
        confirmPass: [
          { type: 'string', required: true, message: '请再次输入密码', trigger: 'blur' },
          {
            trigger: 'blur',
            validator: (rule, value, next) => {
              value !== this.formData.newPass ? next('两次输入的密码不一致') : next()
            }
          }
        ]
      }
    }
  },
  computed: {
    isEdit () {
      return this.$route.path === '/password/edit'
    }
  },
  methods: {
    submit () {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          let pack = { newPass: this.formData.newPass }
          if (this.isEdit) {
            pack.currentPass = this.formData.currentPass
          } else {
            pack.context = 'reset'
          }
          userApi.updatePassword(pack).then((data) => {
            if (data.errCode) {
              this.errMsg = data.errMsg
            } else {
              this.saved = true
              this.$Message.success('密码修改成功')
              this.$router.replace('/settings')
            }
            this.loading = false
          })
        }
      })
    }
  }
}
</script>

<style lang="less">
.password-edit {
  width: 400px;
  // padding: 50px;
  margin: 100px auto;
}
</style>
